package sdu.icat.pj.support;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import sdu.icat.pj.support.Query;
import sdu.icat.pj.util.InstanceUtil;

public class SimpleSpecification<T> implements Specification<T>{

    private Map<String,Object> params = null;

    private Class<T> cls = null;

    public SimpleSpecification(Map<String,Object> params,Class<T> cls) {
	this.params = params;
	this.cls = cls;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
	    CriteriaBuilder cb) {
	List<Predicate> predicates = InstanceUtil.newArrayList();
	Field[] fields = cls.getDeclaredFields();
	for(String property:params.keySet()) {
	    if(contains(fields,property)) {
		predicates.add(cb.equal(root.get(property),params.get(property)));
		continue;
	    }
	}
	return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
    }

    private boolean contains(Field[] fields,String property) {
	for(int i=0;i<fields.length;i++) {
	    String propertyName = fields[i].getName();
	    if(propertyName.equals(property))
		return true;
	}
	return false;
    }


}
